-
Notifications
You must be signed in to change notification settings - Fork 114
/
ActorManager.cs
1501 lines (1291 loc) · 56.3 KB
/
ActorManager.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
namespace Microsoft.ServiceFabric.Actors.Runtime
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Fabric;
using System.Globalization;
using System.Linq;
using System.Runtime.ExceptionServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.ServiceFabric.Actors.Diagnostics;
using Microsoft.ServiceFabric.Actors.Query;
using Microsoft.ServiceFabric.Actors.Remoting;
using Microsoft.ServiceFabric.Actors.Runtime.Migration;
using Microsoft.ServiceFabric.Services.Common;
using Microsoft.ServiceFabric.Services.Remoting;
using Microsoft.ServiceFabric.Services.Remoting.V2;
using SR = Microsoft.ServiceFabric.Actors.SR;
internal sealed class ActorManager : IActorManager
{
private const string TraceType = "ActorManager";
private const string ReceiveReminderMethodName = "ReceiveReminderAsync";
private readonly string traceId;
private readonly ActorService actorService;
private readonly Random random = new Random();
private readonly ActorMethodContext reminderMethodContext;
private readonly ConcurrentDictionary<ActorId, ActorBase> activeActors;
private readonly ConcurrentDictionary<ActorId, ConcurrentDictionary<string, ActorReminder>> remindersByActorId;
private readonly DiagnosticsEventManager diagnosticsEventManager;
private readonly IActorEventManager eventManager;
private IDiagnosticsManager diagnosticsManager;
private bool isClosed;
private Timer gcTimer;
private Task loadRemindersTask;
internal ActorManager(ActorService actorService)
{
this.actorService = actorService;
this.traceId = actorService.Context.TraceId;
this.diagnosticsManager = new DiagnosticsManager(actorService);
this.diagnosticsEventManager = this.diagnosticsManager.DiagnosticsEventManager;
this.eventManager = new ActorEventManager(actorService.ActorTypeInformation);
this.isClosed = false;
this.activeActors = new ConcurrentDictionary<ActorId, ActorBase>();
this.remindersByActorId = new ConcurrentDictionary<ActorId, ConcurrentDictionary<string, ActorReminder>>();
this.reminderMethodContext = ActorMethodContext.CreateForReminder(ReceiveReminderMethodName);
// Don't capture the current ExecutionContext and its AsyncLocals onto the timer
bool restoreFlow = false;
AsyncFlowControl asyncFlowControl = default(AsyncFlowControl);
try
{
if (!ExecutionContext.IsFlowSuppressed())
{
asyncFlowControl = ExecutionContext.SuppressFlow();
restoreFlow = true;
}
this.gcTimer = new Timer(this.RunGarbageCollection, null, Timeout.Infinite, Timeout.Infinite);
}
finally
{
// Restore the current ExecutionContext
if (restoreFlow)
{
asyncFlowControl.Undo();
}
}
}
public ActorService ActorService
{
get { return this.actorService; }
}
public DiagnosticsEventManager DiagnosticsEventManager
{
get { return this.diagnosticsEventManager; }
}
public bool IsClosed
{
get { return this.isClosed; }
}
public bool HasRemindersLoaded
{
get { return (this.loadRemindersTask != null && this.loadRemindersTask.IsCompleted); }
}
public ActorEventSource TraceSource => ActorTrace.Source;
private IActorStateProvider StateProvider
{
get { return this.actorService.StateProvider; }
}
private IActorActivator ActorActivator
{
get { return this.actorService.ActorActivator; }
}
public Task OpenAsync(IServicePartition partition, CancellationToken cancellationToken)
{
ActorTrace.Source.WriteInfoWithId(TraceType, this.traceId, "Opening ...");
this.ThrowIfClosed();
this.ArmGcTimer();
ActorTrace.Source.WriteInfoWithId(TraceType, this.traceId, "Opened.");
return TaskDone.Done;
}
public async Task CloseAsync(CancellationToken cancellationToken)
{
ActorTrace.Source.WriteInfoWithId(TraceType, this.traceId, "Closing ...");
this.isClosed = true;
await this.CleanupRemindersAsync();
this.DisposeDiagnosticsManager();
ActorTrace.Source.WriteInfoWithId(TraceType, this.traceId, "Closed.");
}
public void Abort()
{
ActorTrace.Source.WriteInfoWithId(TraceType, this.traceId, "Aborting...");
this.isClosed = true;
this.CleanupRemindersAsync().ContinueWith(t => t.Exception);
this.DisposeDiagnosticsManager();
ActorTrace.Source.WriteInfoWithId(TraceType, this.traceId, "Aborted.");
}
#if !DotNetCoreClr
public Task<byte[]> InvokeAsync(
ActorId actorId,
int interfaceId,
int methodId,
string callContext,
byte[] requestMsgBody,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
this.ThrowIfClosed();
this.ThrowIfMigrationInProgress();
var methodDispatcher = this.actorService.MethodDispatcherMapV1.GetDispatcher(interfaceId, methodId);
var actorMethodName = methodDispatcher.GetMethodName(methodId);
var actorMethodContext = ActorMethodContext.CreateForActor(actorMethodName);
var deserializationStartTime = DateTime.UtcNow;
var requestBody = methodDispatcher.DeserializeRequestMessageBody(requestMsgBody);
this.DiagnosticsEventManager.ActorRequestDeserializationFinish(deserializationStartTime);
return this.DispatchToActorAsync<byte[]>(
actorId: actorId,
actorMethodContext: actorMethodContext,
createIfRequired: true,
actorFunc:
(actor, innerCancellationToken) =>
this.ActorMethodDispatch(
methodDispatcher,
actor,
interfaceId,
methodId,
requestBody,
innerCancellationToken),
callContext: callContext,
timerCall: false,
cancellationToken: cancellationToken);
}
#endif
public async Task<T> DispatchToActorAsync<T>(
ActorId actorId,
ActorMethodContext actorMethodContext,
bool createIfRequired,
Func<ActorBase, CancellationToken, Task<T>> actorFunc,
string callContext,
bool timerCall,
CancellationToken cancellationToken)
{
this.ThrowIfClosed();
this.ThrowIfMigrationInProgress();
ExceptionDispatchInfo exceptionInfo = null;
Exception exception = null;
var retval = default(T);
// get activeActor from the activeActors table
using (var actorUseScope = this.GetActor(actorId, createIfRequired, timerCall))
{
var actor = actorUseScope.Actor;
// ***
// START: CRITICAL CODE
// ***
// Emit diagnostic info - before acquiring actor lock
var lockAcquireStartTime = this.DiagnosticsEventManager.AcquireActorLockStart(actor);
ActorTrace.Source.WriteInfoWithId(
TraceType,
this.traceId,
"Acquiring lock for actor: {0}, actor method: {1}",
actorId,
actorMethodContext.MethodName);
DateTime? lockAcquireFinishTime = null;
try
{
await
actor.ConcurrencyLock.Acquire(
callContext,
async innerActor => await this.HandleDirtyStateAsync(innerActor),
cancellationToken);
}
catch (Exception ex)
{
// Emit diagnostic info - failed to acquire actor lock
this.DiagnosticsEventManager.AcquireActorLockFailed(actor);
ActorTrace.Source.WriteWarningWithId(
TraceType,
this.traceId,
"Failed to acquire lock for actor: {0}, actor method: {1}, exception - {2}",
actorId,
actorMethodContext.MethodName,
ex.ToString());
throw;
}
// WARNING: DO NOT PUT ANY CODE BETWEEN CONCURRENCY LOCK ACQUIRE AND TRY
// THE LOCK NEEDS TO BE RELEASED IF THERE IS ANY EXCEPTION
try
{
// Emit diagnostic info - after acquiring actor lock
lockAcquireFinishTime = this.DiagnosticsEventManager.AcquireActorLockFinish(
actor,
lockAcquireStartTime);
ActorTrace.Source.WriteInfoWithId(
TraceType,
this.traceId,
"Acquired lock for actor: {0}, actor method: {1}",
actorId,
actorMethodContext.MethodName);
retval =
await
this.DispatchToActorConcurrencyLockHeldAsync<T>(
actorId,
actorMethodContext,
actor,
actorFunc,
callContext,
cancellationToken);
}
catch (Exception e)
{
exception = e;
try
{
exceptionInfo = ExceptionDispatchInfo.Capture(e);
}
catch
{
// ignored
}
}
// WARNING: DO NOT PUT ANY CODE BELOW BEFORE THE LOCK IS RELEASED
// BECAUSE WE ARE NOT INSIDE A TRY-CATCH BLOCK
//
// signal that current execution is finished on this actor
// since there is no call pending or this was the first actor call in the callContext
await actor.ConcurrencyLock.ReleaseContext(callContext);
// Emit diagnostic info - after releasing actor lock
this.DiagnosticsEventManager.ReleaseActorLock(lockAcquireFinishTime);
// ***
// END: CRITICAL CODE
// ***
if (exceptionInfo != null)
{
exceptionInfo.Throw();
}
else if (exception != null)
{
throw exception;
}
return retval;
}
}
public Task<IServiceRemotingResponseMessageBody> InvokeAsync(
ActorId actorId,
int interfaceId,
int methodId,
string callContext,
IServiceRemotingRequestMessageBody requestMsgBody,
IServiceRemotingMessageBodyFactory remotingMessageBodyFactory,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
this.ThrowIfClosed();
this.ThrowIfMigrationInProgress();
var methodDispatcher = this.actorService.MethodDispatcherMapV2.GetDispatcher(interfaceId, methodId);
var actorMethodName = methodDispatcher.GetMethodName(methodId);
var actorMethodContext = ActorMethodContext.CreateForActor(actorMethodName);
return this.DispatchToActorAsync<IServiceRemotingResponseMessageBody>(
actorId: actorId,
actorMethodContext: actorMethodContext,
createIfRequired: true,
actorFunc:
(actor, innerCancellationToken) =>
this.ActorMethodDispatch(
methodDispatcher,
actor,
interfaceId,
methodId,
requestMsgBody,
remotingMessageBodyFactory,
innerCancellationToken),
callContext: callContext,
timerCall: false,
cancellationToken: cancellationToken);
}
public Task SubscribeAsync(ActorId actorId, int eventInterfaceId, IActorEventSubscriberProxy subscriber)
{
this.ThrowIfMigrationInProgress();
return this.eventManager.SubscribeAsync(actorId, eventInterfaceId, subscriber);
}
public Task UnsubscribeAsync(ActorId actorId, int eventInterfaceId, Guid subscriberId)
{
this.ThrowIfMigrationInProgress();
return this.eventManager.UnsubscribeAsync(actorId, eventInterfaceId, subscriberId);
}
public TEvent GetEvent<TEvent>(ActorId actorId)
{
return (TEvent)(object)this.eventManager.GetActorEventProxy(actorId, typeof(TEvent));
}
public async Task<IActorReminder> RegisterOrUpdateReminderAsync(
ActorId actorId,
string reminderName,
byte[] state,
TimeSpan dueTime,
TimeSpan period,
bool saveState = true)
{
this.ThrowIfMigrationInProgress();
var reminder = new ActorReminder(actorId, this, reminderName, state, dueTime, period);
await this.RegisterOrUpdateReminderAsync(reminder, dueTime, saveState);
return reminder;
}
public IActorReminder GetReminder(string reminderName, ActorId actorId)
{
this.ThrowIfClosed();
if (this.remindersByActorId.TryGetValue(actorId, out var actorReminders))
{
if (actorReminders.TryGetValue(reminderName, out var reminder))
{
return reminder;
}
throw new ReminderNotFoundException(string.Format(SR.ReminderNotFound, reminderName, actorId));
}
throw new ReminderNotFoundException(string.Format(SR.ReminderNotFound, reminderName, actorId));
}
public async Task UnregisterReminderAsync(string reminderName, ActorId actorId, bool removeFromStateProvider)
{
this.ThrowIfClosed();
this.ThrowIfMigrationInProgress();
ActorTrace.Source.WriteInfoWithId(
TraceType,
this.traceId,
"Unregistering reminder for actor {0}, reminderName {1}",
actorId,
reminderName);
if (removeFromStateProvider)
{
await this.StateProvider.DeleteReminderAsync(actorId, reminderName);
}
if (this.remindersByActorId.TryGetValue(actorId, out var actorReminders))
{
if (actorReminders.TryRemove(reminderName, out var reminder))
{
reminder.Dispose();
// If this was last reminder for this actor, remove entry for actor.
// Though space occupied by entry is small, for application that
// create and delete actors at high frequency, this will start
// piling up redundant memory until the current primary failover happens.
if (actorReminders.Count == 0)
{
this.remindersByActorId.TryRemove(actorId, out actorReminders);
}
}
else
{
throw new ReminderNotFoundException(string.Format(SR.ReminderNotFound, reminderName, actorId));
}
}
else
{
throw new ReminderNotFoundException(string.Format(SR.ReminderNotFound, reminderName, actorId));
}
}
public Task StartLoadingRemindersAsync(CancellationToken cancellationToken)
{
this.ThrowIfMigrationInProgress();
this.loadRemindersTask = this.LoadRemindersAsync(cancellationToken);
return this.loadRemindersTask;
}
public async Task FireReminderAsync(ActorReminder reminder)
{
this.ThrowIfMigrationInProgress();
var rearmTimer = true;
try
{
ActorTrace.Source.WriteInfoWithId(
TraceType,
this.traceId,
"Firing reminder ({0}) for actor ({1})",
reminder.Name,
reminder.OwnerActorId.GetStorageKey());
using (var actorScope = this.GetActor(reminder.OwnerActorId, true, false))
{
var actorBase = actorScope.Actor;
// if Actor is deleted, reminder should not be fired or armed again.
// Its an optimization so that we don't fire the reminder if the actor
// is marked for deletion.
if (actorBase.MarkedForDeletion)
{
rearmTimer = false;
return;
}
if (this.actorService.ActorTypeInformation.IsRemindable)
{
var actor = (IRemindable)actorBase;
await this.DispatchToActorAsync<byte[]>(
reminder.OwnerActorId,
this.reminderMethodContext,
false,
async (
a,
cancellationTkn) =>
{
await
actor.ReceiveReminderAsync(
reminder.Name,
reminder.State,
reminder.DueTime,
reminder.Period);
return null;
},
Guid.NewGuid().ToString(),
false,
CancellationToken.None);
}
}
}
catch (ActorDeletedException)
{
rearmTimer = false;
}
catch (Exception e)
{
ActorTrace.Source.WriteWarningWithId(
TraceType,
this.traceId,
"Firing reminder {0} for actor {1} caused exception: {2}",
reminder.Name,
reminder.OwnerActorId,
e.ToString());
}
// User may delete or update reminder during ReceiveReminderAsync() call.
// Rearm only if it is still valid.
if (reminder.IsValid() && rearmTimer)
{
if (this.ActorService.Settings.ReminderSettings.AutoDeleteOneTimeReminders &&
this.IsOneTimeReminder(reminder))
{
await this.UnregisterOneTimeReminderAsync(reminder);
}
else
{
await this.UpdateReminderLastCompletedTimeAsync(reminder);
reminder.ArmTimer(reminder.Period);
}
}
}
public async Task DeleteActorAsync(string callContext, ActorId actorId, CancellationToken cancellationToken)
{
this.ThrowIfMigrationInProgress();
ExceptionDispatchInfo exceptionInfo = null;
if (!this.HasRemindersLoaded)
{
throw new ReminderLoadInProgressException(string.Format(
CultureInfo.CurrentCulture,
SR.DeleteActorConflictWithLoadReminders,
actorId));
}
ActorTrace.Source.WriteInfoWithId(
TraceType,
this.traceId,
"[{0}] DeleteActorAsync: Delete call received for actor {1}",
callContext,
actorId);
// Use ActorConcurrencyLock to synchronize with other actor calls.
// If the Actor is active, its ActorConcurrencyLock is used for synchronization.
// If the actor is inactive, a Dummy Actor instance is created and its ActorConcurrencyLock is used for synchronization.
using (
var actorUseScope = this.GetActor(
actorId: actorId,
createIfRequired: true,
timerCall: false,
createDummyActor: true))
{
var actor = actorUseScope.Actor;
await
actor.ConcurrencyLock.Acquire(
callContext,
(async innerActor => await this.HandleDirtyStateAsync(innerActor)),
ActorReentrancyMode.Disallowed,
cancellationToken);
ActorTrace.Source.WriteInfoWithId(
TraceType,
this.traceId,
"[{0}] DeleteActorAsync: Acquired ReentrancyGuard for actor {1}.",
callContext,
actorId);
// If Actor is already marked for deletion by other delete call, do not try to delete it again.
if (actor.MarkedForDeletion)
{
ActorTrace.Source.WriteInfoWithId(
TraceType,
this.traceId,
"[{0}] DeleteActorAsync: Actor {1} is already marked for deletion, returning without processing this delete call.",
callContext,
actorId);
}
else
{
try
{
this.ThrowIfClosed();
cancellationToken.ThrowIfCancellationRequested();
actor.MarkedForDeletion = true;
// Remove actor state(and reminders) first and then unregister reminders as RemoveActorState can throw
// and in this case reminders should not be unregistered.
ActorTrace.Source.WriteInfoWithId(
TraceType,
this.traceId,
"[{0}] DeleteActorAsync: Removing actor state and reminders for Actor {1}.",
callContext,
actor.Id);
await this.StateProvider.RemoveActorAsync(actorId, cancellationToken);
ActorTrace.Source.WriteInfoWithId(
TraceType,
this.traceId,
"[{0}] DeleteActorAsync: Unregistering all reminders for Actor {1}.",
callContext,
actor.Id);
if (this.remindersByActorId.TryGetValue(actorId, out var actorReminders))
{
var reminderNames = actorReminders.Values.Select(r => r.Name).ToList().AsReadOnly();
foreach (var reminderName in reminderNames)
{
await this.UnregisterReminderAsync(reminderName, actor.Id, false);
}
}
ActorTrace.Source.WriteInfoWithId(
TraceType,
this.traceId,
"[{0}] DeleteActorAsync: Clearing event subscriptions for actor {1}.",
callContext,
actorId);
await this.eventManager.ClearAllSubscriptions(actorId);
}
catch (Exception e)
{
ActorTrace.Source.WriteInfoWithId(
TraceType,
this.traceId,
"[{0}] DeleteActorAsync: Removing state for actor {1} caused exception {2}, {3}.",
callContext,
actorId,
e.Message,
e.StackTrace);
exceptionInfo = ExceptionDispatchInfo.Capture(e);
}
try
{
// deactivate must happen outside of above try catch to avoid scenarios
// in which Remove actor state and reminder from state provider throws.
if (this.activeActors.TryRemove(actorId, out var removedActor))
{
ActorTrace.Source.WriteInfoWithId(
TraceType,
this.traceId,
"[{0}] DeleteActorAsync: Deactivating actor {1}",
callContext,
actorId);
await this.DeactivateActorAsync(removedActor);
ActorTrace.Source.WriteInfoWithId(
TraceType,
this.traceId,
"[{0}] DeleteActorAsync: Completed Deactivation of actor {1}",
callContext,
actorId);
}
}
catch (Exception e)
{
// Catch exception as ReentrantGuard must be released.
ActorTrace.Source.WriteInfoWithId(
TraceType,
this.traceId,
"[{0}] DeleteActorAsync: Deactivating actor {1} caused exception {2}, {3}.",
callContext,
actorId,
e.Message,
e.StackTrace);
exceptionInfo = ExceptionDispatchInfo.Capture(e);
}
}
await actor.ConcurrencyLock.ReleaseContext(callContext);
if (exceptionInfo != null)
{
exceptionInfo.Throw();
}
return;
}
}
/// <summary>
/// Returns Actors list by querying state provider for Actors.
/// </summary>
public async Task<PagedResult<ActorInformation>> GetActorsFromStateProvider(
ContinuationToken continuationToken,
CancellationToken cancellationToken)
{
// Get the Actors list from State provider and mark them Active or Inactive
const int maxCount = PagedResult<ActorInformation>.MaxItemsToReturn;
var queryResult = await this.StateProvider.GetActorsAsync(maxCount, continuationToken, cancellationToken);
cancellationToken.ThrowIfCancellationRequested();
var actorInfos =
queryResult.Items.Select(x => new ActorInformation(x, this.activeActors.ContainsKey(x))).ToList();
return new PagedResult<ActorInformation>()
{
Items = actorInfos,
ContinuationToken = queryResult.ContinuationToken,
};
}
public async Task<ReminderPagedResult<KeyValuePair<ActorId, List<ActorReminderState>>>> GetRemindersFromStateProviderAsync(
ActorId actorId,
ContinuationToken continuationToken,
CancellationToken cancellationToken)
{
return await this.StateProvider.GetRemindersAsync(
ReminderPagedResult<KeyValuePair<ActorId, List<ActorReminderState>>>.GetDefaultPageSize(),
actorId,
continuationToken,
cancellationToken);
}
public string GetActorTraceId(ActorId actorId)
{
return ActorTrace.GetTraceIdForActor(
this.actorService.Context.PartitionId,
this.actorService.Context.ReplicaId,
actorId);
}
internal ActorUseScope GetActor(
ActorId actorId,
bool createIfRequired,
bool timerCall,
bool createDummyActor = false)
{
return createIfRequired
? this.GetOrCreateActor(actorId, timerCall, createDummyActor)
: this.GetExistingActor(actorId, timerCall);
}
internal Task OnPreActivateAsync(ActorBase actor)
{
return ResetStateAsync(actor);
}
internal async Task OnPostActivateAsync(ActorBase actor)
{
await this.StateProvider.ActorActivatedAsync(actor.Id);
await actor.OnPostActivateAsync();
}
internal async Task HandleDirtyStateAsync(ActorBase actor)
{
ActorTrace.Source.WriteInfoWithId(
TraceType,
this.traceId,
"Reloading state for Actor {0}, since IsDirty state is {1}",
actor.Id,
actor.IsDirty);
await ResetStateAsync(actor);
actor.IsDirty = false;
}
internal ActorBase CreateDummyActor(ActorId actorId)
{
ActorTrace.Source.WriteInfoWithId(
TraceType,
this.traceId,
"Creating DummyActor to delete inactive actor {0}",
actorId);
return new DummyActor(this.actorService, actorId);
}
internal Task OnPreInvokeAsync(ActorBase actor, ActorMethodContext actorMethodContext)
{
this.ThrowIfClosed();
return actor.OnPreActorMethodAsyncInternal(actorMethodContext);
}
internal async Task OnPostInvokeAsync(ActorBase actor, ActorMethodContext actorMethodContext)
{
this.ThrowIfClosed();
await actor.OnPostActorMethodAsyncInternal(actorMethodContext);
await SaveStateAsync(actor);
}
#region Test Helpers
internal bool Test_HasAnyReminders()
{
return !(this.remindersByActorId.IsEmpty);
}
internal bool Test_ReminderDictionaryHasEntry(ActorId actorId)
{
return this.remindersByActorId.ContainsKey(actorId);
}
#endregion
private static bool ShouldInitialize(ActorBase actor)
{
return (actor.IsInitialized != true);
}
private static Task ResetStateAsync(ActorBase actor)
{
return actor.ResetStateAsyncInternal();
}
private static Task SaveStateAsync(ActorBase actor)
{
return actor.SaveStateAsyncInternal();
}
#if !DotNetCoreClr
private Task<byte[]> ActorMethodDispatch(
Remoting.V1.Builder.ActorMethodDispatcherBase methodDispatcher,
ActorBase actor,
int interfaceId,
int methodId,
object requestBody,
CancellationToken innerCancellationToken)
{
var actorInterfaceMethodKey = DiagnosticsEventManager.GetInterfaceMethodKey(
(uint)interfaceId,
(uint)methodId);
this.DiagnosticsEventManager.ActorMethodStart(actorInterfaceMethodKey, actor, RemotingListenerVersion.V1);
Task<object> dispatchTask;
try
{
dispatchTask = methodDispatcher.DispatchAsync(actor, methodId, requestBody, innerCancellationToken);
}
catch (Exception e)
{
this.DiagnosticsEventManager.ActorMethodFinish(
actorInterfaceMethodKey,
actor,
e,
RemotingListenerVersion.V1);
throw;
}
return dispatchTask.ContinueWith(
t =>
{
object responseMsgBody = null;
try
{
responseMsgBody = t.GetAwaiter().GetResult();
}
catch (Exception e)
{
this.DiagnosticsEventManager.ActorMethodFinish(
actorInterfaceMethodKey,
actor,
e,
RemotingListenerVersion.V1);
throw;
}
this.DiagnosticsEventManager.ActorMethodFinish(
actorInterfaceMethodKey,
actor,
null,
RemotingListenerVersion.V1);
var serializationStartTime = DateTime.UtcNow;
var serializedResponse = methodDispatcher.SerializeResponseMessageBody(responseMsgBody);
this.DiagnosticsEventManager.ActorResponseSerializationFinish(serializationStartTime);
return serializedResponse;
},
TaskContinuationOptions.ExecuteSynchronously);
}
#endif
private Task<IServiceRemotingResponseMessageBody> ActorMethodDispatch(
Remoting.V2.Builder.ActorMethodDispatcherBase methodDispatcher,
ActorBase actor,
int interfaceId,
int methodId,
IServiceRemotingRequestMessageBody requestBody,
IServiceRemotingMessageBodyFactory remotingMessageBodyFactory,
CancellationToken innerCancellationToken)
{
var actorInterfaceMethodKey =
DiagnosticsEventManager.GetInterfaceMethodKey((uint)interfaceId, (uint)methodId);
this.DiagnosticsEventManager.ActorMethodStart(actorInterfaceMethodKey, actor, RemotingListenerVersion.V2);
Task<IServiceRemotingResponseMessageBody> dispatchTask;
try
{
dispatchTask = methodDispatcher.DispatchAsync(
actor,
methodId,
requestBody,
remotingMessageBodyFactory,
innerCancellationToken);
}
catch (Exception e)
{
this.DiagnosticsEventManager.ActorMethodFinish(
actorInterfaceMethodKey,
actor,
e,
RemotingListenerVersion.V2);
throw;
}
return dispatchTask.ContinueWith(
t =>
{
IServiceRemotingResponseMessageBody responseMsgBody = null;
try
{
responseMsgBody = t.GetAwaiter().GetResult();
}
catch (Exception e)
{
this.DiagnosticsEventManager.ActorMethodFinish(
actorInterfaceMethodKey,
actor,
e,
RemotingListenerVersion.V2);
throw;
}
this.DiagnosticsEventManager.ActorMethodFinish(
actorInterfaceMethodKey,
actor,
null,
RemotingListenerVersion.V2);
return responseMsgBody;
},
TaskContinuationOptions.ExecuteSynchronously);
}
private async Task<T> DispatchToActorConcurrencyLockHeldAsync<T>(
ActorId actorId,
ActorMethodContext actorMethodContext,
ActorBase actor,
Func<ActorBase, CancellationToken, Task<T>> actorFunc,
string callContext,
CancellationToken cancellationToken)
{
var retval = default(T);
// if this actor has been deleted or is a dummy actor, then calls must be made on new object.
if (actor.MarkedForDeletion || actor.IsDummy)
{
// Deleted Actor, Method calls will be retried by Actor Proxy.
throw new ActorDeletedException(string.Format(
CultureInfo.CurrentCulture,
SR.ActorDeletedExceptionMessage,
actorId));
}
this.ThrowIfClosed();
// set the incoming callContext as the new logical call context, before
// making calls to the actor, so that when the actor makes call this context
// flows through
ActorLogicalCallContext.Set(callContext);
// initialize the actor if needed
if (ShouldInitialize(actor))
{
await this.InitializeAsync(actor);
}
try
{
// invoke the function of the actor
await this.OnPreInvokeAsync(actor, actorMethodContext);
retval = await actorFunc.Invoke(actor, cancellationToken);
await this.OnPostInvokeAsync(actor, actorMethodContext);